package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import messages.ConnectTo;
import messages.GameEventDispatcher;
import messages.GameEventListener;
import messages.GameMessage;

public class ConnectionMenu extends JFrame implements ActionListener, GameEventDispatcher{
	
	private ArrayList<GameEventListener> listeners;
	private JTextField server;
	private JTextField port;
	

	private static final long serialVersionUID = -4736130268216209221L;

	public ConnectionMenu(){
		super("Connect to server");
		JPanel container = new JPanel(new BorderLayout());
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		JPanel input = new JPanel();
		server = new JTextField(30);
		port = new JTextField(5);
		JTextField serverMessage = new JTextField("Address: ");
		serverMessage.setEditable(false);
		serverMessage.setFocusable(false);
		JTextField portMessage = new JTextField("Port: ");
		portMessage.setEditable(false);
		portMessage.setFocusable(false);
		port.setText("5491");
		input.add(serverMessage);
		input.add(server);
		input.add(portMessage);
		input.add(port);
		
		JPanel buttons = new JPanel();
		JButton connect = new JButton("Connect");
		JButton cancel = new JButton("Cancel");
		cancel.setActionCommand("cancel");
		cancel.addActionListener(this);
		connect.setActionCommand("connect");
		connect.addActionListener(this);
		buttons.add(connect);
		buttons.add(cancel);
		
		container.add(input, BorderLayout.NORTH);
		container.add(buttons, BorderLayout.SOUTH);
		
		this.add(container);
		pack();
		setAlwaysOnTop(true);
		container.setVisible(true);
		
	}
	

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();
		if(actionCommand.equals("cancel")){
			this.dispose();
		}
		if(actionCommand.equals("connect")){
			/*TODO
			 * send message of connection to listener
			 */
			ConnectTo connection = new ConnectTo(server.getText(), port.getText());
			if(connection==null)
				return;
			sendEvent(connection);
			this.dispose();
		}
	}

	@Override
	public void registerGameListener(GameEventListener listener) {
		if(listeners==null)
			listeners = new ArrayList<GameEventListener>();
		listeners.add(listener);
		
	}

	@Override
	public void sendEvent(GameMessage event) {
		for(GameEventListener listener:listeners)
			listener.gameEvent(event);
	}

}
